package com.walnut.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/uploadFile")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 上传文件的存储路径
    private static final String UPLOAD_DIRECTORY = "C:\\Users\\14003\\Desktop\\javaweb\\web\\image";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        File uploadDir = new File(UPLOAD_DIRECTORY);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        try {
            for (Part filePart : request.getParts()) {
                if ("foodImg".equals(filePart.getName())) {
                    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
                    String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                    filePart.write(filePath);

                    // 构建图片URL
                    String fileUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +
                            request.getContextPath() + "/image/" + fileName;

                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(fileUrl);

                }
            }
        } catch (Exception e) {
            throw new ServletException("File upload failed", e);
        }
    }
}
